package 多线程.三个线程实现顺序打印;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock+全局变量state
 */
public class Test10 {
    private static Lock lock = new ReentrantLock();
    //判断是否执行：1表示应该A执行，2表示应该B执行，3表示应该C执行
    private static int state = 1;

    public static void main(String[] args) {
        Test10 t = new Test10();
        Thread t1 = new Thread(){
            @Override
            public void run() {
                t.printA();
            }
        };
        Thread t2 = new Thread(){
            @Override
            public void run() {
                t.printB();
            }
        };
        Thread t3 = new Thread(){
            @Override
            public void run() {
                t.printC();
            }
        };
        t1.start();
        t2.start();
        t3.start();
    }

    public static void printA(){
        while (state < 4){
            try {
                lock.lock();
                while (state == 1){
                    System.out.println("A");
                    state++;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void printB(){
        while (state < 4){
            try {
                lock.lock();
                while (state == 2){
                    System.out.println("B");
                    state++;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void printC() {
        while (state < 4){
            try {
                lock.lock();
                while (state == 3){
                    System.out.println("C");
                    state++;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
